<template>
  <div class="register-page">
    <!-- Banner 图片 -->
    <div class="banner">
      <img
        src="@/assets/images/banner.jpg"
        alt="学校banner"
        class="banner-image"
      />
      <div class="banner-overlay"></div>
      <div class="banner-content">
        <div class="banner-title">
          <h1 class="platform-name">启迪智慧</h1>
          <p class="platform-desc">实验室管理系统</p>
        </div>
      </div>
    </div>

    <!-- 注册表单 -->
    <div class="register-container">
      <div class="register-box">
        <h2 class="title">用户注册</h2>

        <el-form
          ref="registerFormRef"
          :model="registerForm"
          :rules="registerRules"
          class="register-form"
        >
          <el-form-item prop="name">
            <el-input
              v-model="registerForm.name"
              placeholder="请输入用户名"
              size="large"
              prefix-icon="User"
            />
          </el-form-item>

          <el-form-item prop="userCode">
            <el-input
              v-model="registerForm.userCode"
              placeholder="请输入账户"
              size="large"
              prefix-icon="UserFilled"
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="请输入密码"
              size="large"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>

          <el-form-item prop="confirmPassword">
            <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="请重复输入密码"
              size="large"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              size="large"
              class="register-btn"
              @click="handleRegister"
              :loading="loading"
            >
              注册
            </el-button>
          </el-form-item>
        </el-form>

        <div class="login-link">
          <span>已有账号？</span>
          <router-link to="/login" class="link">立即登录</router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElForm } from "element-plus";
import { JSEncrypt } from "jsencrypt";
import { registerAPI, getPublicKeyAPI, RegisterType } from "@/api/service/user";

const router = useRouter();
const registerFormRef = ref<InstanceType<typeof ElForm>>();
const loading = ref(false);
const publicKey = ref("");

// 注册表单数据
const registerForm = reactive({
  name: "",
  userCode: "",
  password: "",
  confirmPassword: "",
});

// 确认密码验证
const validateConfirmPassword = (rule: any, value: string, callback: any) => {
  if (value !== registerForm.password) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};

// 表单验证规则
const registerRules = {
  name: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 20, message: "用户名长度在2到20个字符", trigger: "blur" },
  ],
  userCode: [
    { required: true, message: "请输入账户", trigger: "blur" },
    { min: 3, max: 20, message: "账户长度在3到20个字符", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9_]+$/,
      message: "账户只能包含字母、数字和下划线",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 8, max: 20, message: "密码长度在8到20个字符", trigger: "blur" },
    {
      pattern: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*(),.?":{}|<>])/,
      message: "密码必须包含字母、数字和特殊字符",
      trigger: "blur",
    },
  ],
  confirmPassword: [
    { required: true, message: "请重复输入密码", trigger: "blur" },
    { validator: validateConfirmPassword, trigger: "blur" },
  ],
};

// 获取公钥
const getPublicKey = async () => {
  try {
    const response = await getPublicKeyAPI();
    publicKey.value = response as any;
  } catch (error) {
    ElMessage.error("获取加密密钥失败");
  }
};

// 密码加密
const encryptPassword = (password: string) => {
  if (!publicKey.value) {
    ElMessage.error("加密密钥未获取");
    return "";
  }

  const encrypt = new JSEncrypt();
  encrypt.setPublicKey(publicKey.value);
  return encrypt.encrypt(password) || "";
};

// 注册处理
const handleRegister = async () => {
  if (!registerFormRef.value) return;

  await registerFormRef.value.validate((valid: boolean) => {
    if (valid) {
      register();
    }
  });
};

const register = async () => {
  loading.value = true;

  try {
    // 加密密码
    const encryptedPassword = encryptPassword(registerForm.password);
    if (!encryptedPassword) {
      loading.value = false;
      return;
    }

    const registerData: RegisterType = {
      name: registerForm.name,
      userCode: registerForm.userCode,
      encryptedPassword,
      ogaCode: "defaultOgaCode",
    };

    await registerAPI(registerData);
    ElMessage.success("注册成功，请登录");
    // 跳转到登录页面
    router.push("/login");
  } catch (error: any) {
    if (error) {
      ElMessage.error(error);
    } else {
      ElMessage.error("注册失败，请检查网络连接");
    }
  } finally {
    loading.value = false;
  }
};

// 页面初始化
onMounted(() => {
  getPublicKey();
});
</script>

<style scoped lang="scss">
.register-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.banner {
  position: relative;
  width: 100%;
  margin-bottom: 20px;
  overflow: hidden;

  .banner-image {
    width: 100%;
    height: auto;
    display: block;
  }

  .banner-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(
      135deg,
      rgb(102, 126, 234, 0.8) 0%,
      rgb(118, 75, 162, 0.8) 100%
    );
  }

  .banner-content {
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    z-index: 2;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
  }

  .banner-title {
    .platform-name {
      font-size: 3.6rem;
      font-weight: 700;
      color: white;
      margin: 0 0 8px 0;
      text-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
      letter-spacing: 2px;
    }

    .platform-desc {
      font-size: 3rem;
      color: rgba(255, 255, 255, 0.9);
      margin: 0;
      font-weight: 400;
      text-shadow: 0 1px 4px rgba(0, 0, 0, 0.3);
      letter-spacing: 1px;
    }
  }
}

.register-container {
  position: absolute;
  bottom: 2rem;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  z-index: 99;
}

.register-box {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  min-width: 400px;
  max-width: 500px;
  width: 100%;

  .title {
    text-align: center;
    font-size: 28px;
    font-weight: 600;
    color: #333;
    margin-bottom: 30px;
  }

  .register-form {
    .el-form-item {
      margin-bottom: 20px;
    }

    .el-input {
      --el-input-height: 48px;
    }

    .register-btn {
      width: 100%;
      height: 48px;
      font-size: 16px;
      font-weight: 600;
      margin-top: 10px;
    }
  }

  .login-link {
    text-align: center;
    margin-top: 20px;
    color: #666;

    .link {
      color: #409eff;
      text-decoration: none;
      margin-left: 5px;

      &:hover {
        text-decoration: underline;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .banner {
    margin-bottom: 15px;

    .banner-title {
      .platform-name {
        font-size: 24px;
        margin-bottom: 4px;
        letter-spacing: 1px;
      }

      .platform-desc {
        font-size: 14px;
      }
    }
  }

  .register-container {
    padding: 20px 15px;
  }

  .register-box {
    min-width: auto;
    padding: 30px 25px;
  }
}
</style>
